package com.itheima.d1_map_impl;


import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/*
    目标：掌握Map集合下的实现类：HashMap集合的底层原理。

    需求：创建一个HashMap集合，键是学生对象(Student)，值是籍贯(String)。存储三个键值对元素，并遍历

    结论 : HashMap集合要先保证键的唯一,那么键存储的元素必须重写hashCode和equals方法
 */
public class Test1HashMap {
    public static void main(String[] args) {
        // 创建HashMap集合
        HashMap<Student, String> students = new HashMap<>();
        // 新增
        Student timor = new Student("1", "TIMOR", 23);
        students.put(timor, "约德尔人");

        Student dashi = new Student("2", "武器大师", 17);
        students.put(dashi, "诺克萨斯");

        System.out.println(students);

        // 删除
        students.remove(dashi);
        System.out.println(students);

        // 修改
        students.put(timor, "必须死");
        System.out.println(students);

        // 查询
        String lastInfo = students.get(timor);
        System.out.println(lastInfo);

        // 其他方法
        int size = students.size();
        System.out.println("hashmap 长度：" +  size);

        boolean hasKey = students.containsKey(timor);
        System.out.println("是否存在key: " + hasKey);

        boolean empty = students.isEmpty();
        System.out.println("hashmap是否为空: " + empty);

        Collection<String> values = students.values();
        System.out.println("获取值列表: " + values);

//        students.clear(); // 清空字典

        // 2. 循环遍历方法
        // 先取得key值列表
        for (Student student: students.keySet()) {
            System.out.println("key: " + student + " --> value：" + students.get(student));
        }
        // 通过 entrySet 获取键值对集合，再分别获取key和value
        for (Map.Entry entry: students.entrySet()) {
            System.out.println("key: " + entry.getKey() + " --> value: " + entry.getValue());
        }
        // lambda简化函数
        students.forEach((key, value) -> System.out.println(key + " --> " + value));
    }
}
